<script lang="jsx" setup>
import tableData from "../bigData";

const loading = ref(false);
const showTable = ref(false);
const renderTime = ref(null);

const tableColumn = ref([
  {
    key: "id",
    title: "Id",
    dataKey: "id",
    fixed: true,
    width: 100,
    cellRenderer: ({ rowData }) => {
      const { id } = rowData;
      return <div>{id}</div>;
    },
  },
  {
    key: "name",
    title: "名称",
    dataKey: "name",
    width: 200,
    cellRenderer: ({ rowData }) => {
      const { name } = rowData;
      return <div>{name}</div>;
    },
  },
  {
    key: "time",
    title: "时间戳",
    dataKey: "time",
    width: 300,
    cellRenderer: ({ rowData }) => {
      const { time } = rowData;
      return <div>{time}</div>;
    },
  },
]);
const tableLoading = ref("loadFinish"); // loadFinish, loadMore, loadAll
const tableActiveData = ref([]);

const touchBottom = () => {
  if (tableLoading.value !== "all") {
    tableLoading.value = "more";
    const timer = setTimeout(() => {
      tableLoading.value = "all";
      clearTimeout(timer);
    }, 2000);
  }
};

onMounted(() => {
  // 先展示 loading
  loading.value = true;
  // 200ms 后再修改 table 是否显示，防止和 loading 合并到一个渲染周期，导致 loading 不显示
  setTimeout(() => {
    const startTime = new Date().getTime();
    showTable.value = true;
    loading.value = false;
    // 不用nextTick, 使用nextTick无效, setTimemout宏任务塞入任务队列于页面进程解析生成后执行
    setTimeout(() => (renderTime.value = (new Date().getTime() - startTime) / 1000), 0);
  }, 200);
});
</script>

<template>
  <PageMain
    name="虚拟表格"
    v-loading="loading"
    element-loading-text="数据加载中..."
  >
    <template #header> 渲染耗时: {{ renderTime }}秒 - 10000条简单数据 </template>
    <div class="main">
      <div class="table">
        <VirtualTable
          :tableData="tableData"
          :tableColumn="tableColumn"
          :tableLoading="tableLoading"
          :config="{
            tableActiveNum: 9,
            tableActiveKey: 'id',
          }"
          v-model:tableActiveData="tableActiveData"
          @touchBottom="touchBottom"
        />
      </div>
      <div class="show">
        <el-card v-for="item in tableActiveData">
          {{ item }}
        </el-card>
      </div>
    </div>
  </PageMain>
</template>

<style lang="scss">
.main {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  .table {
    width: 400px;
    height: 100%;
    box-sizing: border-box;
    border: 1px solid var(--el-border-color);
  }
  .show {
    flex: 1;
    height: 100%;
    padding: 10px;
    box-sizing: border-box;
    background-color: var(--el-border-color);
    margin-left: 10px;
    .el-card {
      margin-bottom: 4px;
    }
  }
}
</style>
